package cn.tedu._05mvcboot04.controller;

import cn.tedu._05mvcboot04.common.response.JsonResult;
import cn.tedu._05mvcboot04.common.response.StatusCode;
import cn.tedu._05mvcboot04.mapper.UserMapper;
import cn.tedu._05mvcboot04.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot04.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot04.pojo.entity.Article;
import cn.tedu._05mvcboot04.pojo.vo.ArticleVO;
import cn.tedu._05mvcboot04.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
@Validated
@Api(tags = "用户模块")
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public JsonResult loginUser(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){

        String username= userLoginDTO.getUsername();
        String password=userLoginDTO.getPassword();
        UserVO userVO = userMapper.selectUser(username,password);
        if (userVO==null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",userVO);
        return JsonResult.ok();
    }

    @ApiOperation(value = "发表文章功能")
    @PostMapping("article")
    public JsonResult insert(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session){
        UserVO userVO =(UserVO) session.getAttribute("user");
//        if (userVO==null){
//            return new JsonResult(StatusCode.NOT_LOGIN);
//        }
        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setUserId(userVO.getId());
        userMapper.insert(article);
        return JsonResult.ok();

    }

    @ApiOperation(value = "查询指定文章功能")
    @PostMapping("selectByArticleId")
    @ApiImplicitParam(name="id",value = "用户id",required = true,dataType = "int")
    public JsonResult selectArticleId(@Range(min = 1,max = 100,message = "文章id在1-100之间") @RequestParam int id){
      ArticleVO articleVO = userMapper.selectByArticledId(id);
      return JsonResult.ok(articleVO);
    }


}
